package org.framework;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2 //开启swagger
//@Profile(value = {"dev","sit"})
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration {


    @Autowired
    private SwaggerProperties swaggerProperties;


    private ApiInfo apiInfo() {


        Contact contact = new Contact(swaggerProperties.getContact().getName(),
                swaggerProperties.getContact().getWebsite(),
                swaggerProperties.getContact().getEmail());


        return new ApiInfoBuilder().title(swaggerProperties.getDoc().getTitle())
                .description(swaggerProperties.getDoc().getDesc())
                .version(swaggerProperties.getDoc().getVersion())
                .contact(contact)
                .build();


    }
    @Bean
    public Docket createRestApi(Environment environment) {




        String[] envs = swaggerProperties.getEnvs(); //允许开启swagger的环境 sit
        Profiles profiles = Profiles.of(envs);


        //获取当前spring的环境
        boolean enable = environment.acceptsProfiles(profiles);




        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(enable)
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasepackage()))
                .paths(PathSelectors.any())
                .build();
    }
}
